import { Injectable, NestInterceptor, ExecutionContext, CallHandler } from '@nestjs/common';
import { Observable } from 'rxjs';
import { map } from 'rxjs/operators';
import { ErrorCode } from '../../constants/error';
import { MyRequest } from '../types/net';
import { MyLoggerService } from '../../common/logger.service';

@Injectable()
export class TransformResInterceptor<T> implements NestInterceptor {

  constructor(
    private readonly logger: MyLoggerService,
  ) {}

  intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
    return next.handle().pipe(map(async (data) => {
      const req = context.switchToHttp().getRequest<MyRequest>();
      const reqEndTime = Date.now();
      const responseTime = reqEndTime - req.reqStartTime;
      this.logger.info({
        data: {
          req: {
            method: 'GET',
            url: req.originalUrl,
            headers: {
              'user-agent': req.headers['user-agent'],
            },
          },
          ip: req.clientIp,
          responseTime,
        },
      });

      if (typeof data === 'undefined') {
        // 请求页面时进入这里
        return data;
      }
      const newData = data as any;
      
      console.log(newData);

      if (typeof newData.statusCode === 'undefined') {
        return {
          data: newData,
          code: ErrorCode.SUCCESS.CODE,
          message: 'success',
        };
      }
      let errorCode, message;
      if (ErrorCode.HasCode(newData.statusCode)) {
        errorCode = newData.statusCode;
        message = ErrorCode.CodeToMessage(errorCode);
      } else {
        errorCode = ErrorCode.ERROR.CODE;
        message = ErrorCode.ERROR.MESSAGE;
      }
      return {
        code: errorCode,
        message,
        data: process.env.NODE_ENV === 'dev' ? {
          nestjs: newData.message,
        } : null,
      };
    }));
  }
}
